// LSP API服务
// 提供语言服务器协议相关功能

import { apiClient, RequestConfig } from './ApiClient';

// LSP相关类型
export interface Position {
  line: number;
  character: number;
}

export interface Range {
  start: Position;
  end: Position;
}

export interface Location {
  uri: string;
  range: Range;
}

export interface CompletionItem {
  label: string;
  kind: CompletionItemKind;
  detail?: string;
  documentation?: string;
  insertText?: string;
  filterText?: string;
  sortText?: string;
  additionalTextEdits?: TextEdit[];
}

export enum CompletionItemKind {
  Text = 1,
  Method = 2,
  Function = 3,
  Constructor = 4,
  Field = 5,
  Variable = 6,
  Class = 7,
  Interface = 8,
  Module = 9,
  Property = 10,
  Unit = 11,
  Value = 12,
  Enum = 13,
  Keyword = 14,
  Snippet = 15,
  Color = 16,
  File = 17,
  Reference = 18,
  Folder = 19,
  EnumMember = 20,
  Constant = 21,
  Struct = 22,
  Event = 23,
  Operator = 24,
  TypeParameter = 25,
}

export interface TextEdit {
  range: Range;
  newText: string;
}

export interface Hover {
  contents: string | string[];
  range?: Range;
}

export interface SymbolInformation {
  name: string;
  kind: SymbolKind;
  location: Location;
  containerName?: string;
}

export enum SymbolKind {
  File = 1,
  Module = 2,
  Namespace = 3,
  Package = 4,
  Class = 5,
  Method = 6,
  Property = 7,
  Field = 8,
  Constructor = 9,
  Enum = 10,
  Interface = 11,
  Function = 12,
  Variable = 13,
  Constant = 14,
  String = 15,
  Number = 16,
  Boolean = 17,
  Array = 18,
  Object = 19,
  Key = 20,
  Null = 21,
  EnumMember = 22,
  Struct = 23,
  Event = 24,
  Operator = 25,
  TypeParameter = 26,
}

export interface Diagnostic {
  range: Range;
  severity: DiagnosticSeverity;
  code?: string | number;
  source?: string;
  message: string;
  relatedInformation?: DiagnosticRelatedInformation[];
}

export enum DiagnosticSeverity {
  Error = 1,
  Warning = 2,
  Information = 3,
  Hint = 4,
}

export interface DiagnosticRelatedInformation {
  location: Location;
  message: string;
}

export interface LspServerInfo {
  serverId: string;
  language: string;
  status: 'starting' | 'running' | 'stopped' | 'error';
  capabilities: ServerCapabilities;
  processId?: number;
  version?: string;
}

export interface ServerCapabilities {
  completionProvider?: boolean;
  hoverProvider?: boolean;
  definitionProvider?: boolean;
  referencesProvider?: boolean;
  documentSymbolProvider?: boolean;
  workspaceSymbolProvider?: boolean;
  documentFormattingProvider?: boolean;
  diagnosticsProvider?: boolean;
}

// LSP API类
export class LspApi {
  // 启动LSP服务器
  async startLspServer(
    language: string,
    config?: RequestConfig
  ): Promise<LspServerInfo> {
    return apiClient.invoke<LspServerInfo>(
      'start_lsp_server',
      { language },
      {
        ...config,
        timeout: 30000, // 30秒超时
      }
    );
  }

  // 停止LSP服务器
  async stopLspServer(
    serverId: string,
    config?: RequestConfig
  ): Promise<boolean> {
    return apiClient.invoke<boolean>(
      'stop_lsp_server',
      { serverId },
      config
    );
  }

  // 重启LSP服务器
  async restartLspServer(
    serverId: string,
    config?: RequestConfig
  ): Promise<LspServerInfo> {
    return apiClient.invoke<LspServerInfo>(
      'restart_lsp_server',
      { serverId },
      {
        ...config,
        timeout: 30000, // 30秒超时
      }
    );
  }

  // 获取LSP服务器状态
  async getLspServerStatus(
    serverId?: string,
    config?: RequestConfig
  ): Promise<LspServerInfo[]> {
    return apiClient.invoke<LspServerInfo[]>(
      'get_lsp_server_status',
      { serverId },
      config
    );
  }

  // 获取自动完成
  async getCompletion(
    filePath: string,
    position: Position,
    language: string,
    config?: RequestConfig
  ): Promise<CompletionItem[]> {
    return apiClient.invoke<CompletionItem[]>(
      'lsp_completion',
      { filePath, position, language },
      config
    );
  }

  // 获取悬停信息
  async getHover(
    filePath: string,
    position: Position,
    language: string,
    config?: RequestConfig
  ): Promise<Hover | null> {
    return apiClient.invoke<Hover | null>(
      'lsp_hover',
      { filePath, position, language },
      config
    );
  }

  // 跳转到定义
  async getDefinition(
    filePath: string,
    position: Position,
    language: string,
    config?: RequestConfig
  ): Promise<Location[]> {
    return apiClient.invoke<Location[]>(
      'lsp_definition',
      { filePath, position, language },
      config
    );
  }

  // 查找引用
  async getReferences(
    filePath: string,
    position: Position,
    language: string,
    includeDeclaration: boolean = false,
    config?: RequestConfig
  ): Promise<Location[]> {
    return apiClient.invoke<Location[]>(
      'lsp_references',
      { filePath, position, language, includeDeclaration },
      config
    );
  }

  // 获取文档符号
  async getDocumentSymbols(
    filePath: string,
    language: string,
    config?: RequestConfig
  ): Promise<SymbolInformation[]> {
    return apiClient.invoke<SymbolInformation[]>(
      'lsp_symbols',
      { filePath, language },
      {
        ...config,
        cache: true,
        cacheKey: `symbols:${filePath}`,
        cacheTTL: 60000, // 1分钟缓存
      }
    );
  }

  // 获取工作区符号
  async getWorkspaceSymbols(
    query: string,
    language?: string,
    config?: RequestConfig
  ): Promise<SymbolInformation[]> {
    return apiClient.invoke<SymbolInformation[]>(
      'lsp_workspace_symbols',
      { query, language },
      config
    );
  }

  // 格式化文档
  async formatDocument(
    filePath: string,
    language: string,
    options?: {
      tabSize?: number;
      insertSpaces?: boolean;
      trimTrailingWhitespace?: boolean;
      insertFinalNewline?: boolean;
    },
    config?: RequestConfig
  ): Promise<TextEdit[]> {
    return apiClient.invoke<TextEdit[]>(
      'lsp_format_document',
      { filePath, language, options },
      config
    );
  }

  // 获取诊断信息
  async getDiagnostics(
    filePath: string,
    language: string,
    config?: RequestConfig
  ): Promise<Diagnostic[]> {
    return apiClient.invoke<Diagnostic[]>(
      'lsp_diagnostics',
      { filePath, language },
      config
    );
  }

  // 监听诊断更新
  async onDiagnosticsUpdate(
    callback: (update: {
      filePath: string;
      diagnostics: Diagnostic[];
      timestamp: string;
    }) => void
  ): Promise<() => void> {
    return apiClient.listen('diagnostics-update', callback);
  }

  // 监听LSP服务器状态变化
  async onServerStatusChange(
    callback: (status: {
      serverId: string;
      language: string;
      status: LspServerInfo['status'];
      message?: string;
      timestamp: string;
    }) => void
  ): Promise<() => void> {
    return apiClient.listen('lsp-status-change', callback);
  }

  // 发送自定义LSP请求
  async sendCustomRequest(
    serverId: string,
    method: string,
    params: any,
    config?: RequestConfig
  ): Promise<any> {
    return apiClient.invoke(
      'lsp_custom_request',
      { serverId, method, params },
      config
    );
  }

  // 发送自定义LSP通知
  async sendCustomNotification(
    serverId: string,
    method: string,
    params: any,
    config?: RequestConfig
  ): Promise<void> {
    return apiClient.invoke<void>(
      'lsp_custom_notification',
      { serverId, method, params },
      config
    );
  }
}

// 全局LSP API实例
export const lspApi = new LspApi();

// 导出类型
export type {
  Position,
  Range,
  Location,
  CompletionItem,
  TextEdit,
  Hover,
  SymbolInformation,
  Diagnostic,
  DiagnosticRelatedInformation,
  LspServerInfo,
  ServerCapabilities,
};
